<template>
	<u-upload
		:fileList="innerValue"
		@afterRead="afterRead"
		@delete="deletePic"
		multiple
		accept="image"
		width="100"
		height="100"
		:disabled="disabled"
		:deletable="!disabled"
		:maxCount="maxCount"
	>
	</u-upload>
</template>

<script>
import { TOKENNAME, HTTP_REQUEST_URL } from "@/config/app.js";
import { useAppStore } from "@/stores/app";
const appStore = useAppStore();
export default {
	name: "upload",
	options: {
		styleIsolation: "shared",
	},
	emits: ["update:modelValue"],
	props: {
		modelValue: {
			type: Array,
			default: () => [],
		},
		model: {
			type: String,
			default: "",
		},
		pid: {
			type: String,
			default: "",
		},
		maxCount: {
			type: Number,
			default: 5,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		maxSize: {
			type: Number,
			default: 1024 * 1024 * 10,
		},
	},
	data() {
		return {
			innerValue: [],
		};
	},
	model: {
		prop: "value",
		event: "input",
	},
	watch: {
		modelValue: {
			deep: true,
			immediate: true,
			handler(newVal, oldVal) {
				this.innerValue = newVal || [];
			},
		},
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this[`innerValue`].splice(event.index, 1);
			this.valueChange();
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`innerValue`].length;
			lists.map((item) => {
				this[`innerValue`].push({
					...item,
					status: "uploading",
					message: this.$t("上传中"),
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this[`innerValue`][fileListLen];
				this[`innerValue`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: "success",
						message: "",
						url: result.url,
					})
				);
				fileListLen++;
			}

			this.valueChange();
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: `${HTTP_REQUEST_URL}/api/front/upload/image?model=${this.model}&pid=${this.pid}`,
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
						[TOKENNAME]: appStore.token,
					},
					filePath: url,
					name: "multipart",
					success: (res) => {
						let data = res.data ? JSON.parse(res.data) : {};
						if (data.code == 200) {
							resolve(data.data);
						} else {
							this[`innerValue`] = this[`innerValue`].filter(item=>item.status==='success')
							this.valueChange();
							reject(data);

							this.$util.Tips({
								title: data.message,
							});
						}
					},
				});
			});
		},
		// 内容发生变化，进行处理
		valueChange() {
			const value = this.innerValue;
			this.$nextTick(() => {
				this.$emit("update:modelValue", value);
			});
		},
	},
};
</script>

<style lang="scss">
:deep() {
	.u-upload__button--disabled {
		display: none !important;
	}
}
</style>
